package com.rykj.energy.task.api.rest;

import com.alibaba.fastjson.JSON;
import com.rykj.energy.common.dto.TaskCameraRelationDto;
import com.rykj.energy.common.enums.BusinessType;
import com.rykj.energy.common.enums.TaskType;
import com.rykj.energy.common.utils.*;
import com.rykj.energy.database.mapper.CameraMapper;
import com.rykj.energy.database.mapper.OrganizationMapper;
import com.rykj.energy.database.pojo.TaskInfo;
import com.rykj.energy.database.pojo.vo.TaskInfoVo;
import com.rykj.energy.database.service.ITaskInfoService;
import com.rykj.energy.database.service.impl.OrganizationServiceImpl;
import com.rykj.energy.task.api.service.ITaskService;
import com.rykj.energy.task.manage.actuator.impl.VideoTaskManage;
import com.rykj.energy.task.manage.vo.TaskInfoDto;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Api(tags = "任务管理模块-基于任务维度")
@Slf4j
@RestController
@RequestMapping("/business/task")
public class TaskController {

    @Autowired
    private ITaskService taskService;

    @Autowired
    private ITaskInfoService taskInfoService;

    @Autowired
    private OrganizationMapper organizationMapper;

    @Autowired
    private CameraMapper cameraMapper;

    @ApiOperation("保存并启动任务信息")
    @PostMapping("/startTasks/{code}")
    public Result startTasks(@PathVariable("code") String code,@RequestBody TaskInfoVo taskInfo){
        try {
            taskService.saveBatchTaskForTask(taskInfo);
        }catch (Exception e){
            log.error("===新增系统异常===",e);
           return Result.failure("新增系统异常");
        }
        return Result.success("保存成功",null);
    }

    @ApiOperation("保存任务信息")
    @PostMapping("/saveTaskInfos/{code}/{taskType}")
    @ApiImplicitParams({
       @ApiImplicitParam(name = "code", value = "任务编码",required = true, paramType = "path"),
       @ApiImplicitParam(name = "taskType", value = "任务类型:video 视频分析,capture 图片分析",required = true, paramType = "path")
    })
    public Result saveTaskInfos(@PathVariable("code") String code,@PathVariable("taskType") String taskType,
                                @RequestBody TaskInfoVo taskInfoVo){
        try {
            if(ObjectUtils.isEmpty(taskInfoVo.getId())||taskInfoVo.getId()==0){
                TaskInfo info = taskInfoService.findByCode(code);
                if(info!=null){
                    throw new Exception("[" + code +"]任务已经存在");
                }
            }
            TaskInfo taskInfo = new TaskInfo();
            BeanUtils.copyProperties(taskInfoVo,taskInfo);
            taskInfo.setTaskType(TaskType.parseByCode(taskType).getCode());
            taskInfo.setTaskCode(code);
            taskInfo.setTaskName(BusinessType.parse(code).bName);
            taskInfoService.saveOrUpdateTask(taskInfo);
        }catch (Exception e){
            log.error("保存任务信息异常===",e);
            return Result.failure(e.getMessage());
        }
        return Result.success("保存成功",null);
    }

    @ApiOperation("根据编码获取任务信息")
    @GetMapping("/getTaskCameraByCode/{code}")
    public Result<TaskInfoVo> getTaskCameraByCode(@PathVariable("code") String code){
        try {
            TaskInfoVo taskInfoVo = taskService.getTaskCameraByCode(code);
            return Result.success(taskInfoVo);
        }catch (Exception e){
            log.error("===根据编码获取任务信息异常===",e);
            return Result.failure("根据编码获取任务信息异常");
        }
    }

    @ApiOperation("获取所有运行中的任务")
    @GetMapping("/getRunTasks")
    public Result<List<TaskInfoDto>> getRunTasks(){
        try {
            List<TaskCameraRelationDto> taskCameras = taskInfoService.findRunTasks();

            List<TaskInfoDto> infoDtoList = new ArrayList<>();
            for(TaskCameraRelationDto taskCameraRelationDto : taskCameras){
                TaskInfoDto taskInfoDto = new TaskInfoDto();
                taskInfoDto.setCamera_id(String.valueOf(taskCameraRelationDto.getCameraId()));
                taskInfoDto.setFlow_id(String.valueOf(taskCameraRelationDto.getTaskId()));
                taskInfoDto.setTask_code(taskCameraRelationDto.getTaskCode());
                taskInfoDto.setPriority(taskCameraRelationDto.getLevel());
                taskInfoDto.setTask_content(taskCameraRelationDto.getBusinessContent());
                taskInfoDto.setOrg_id(taskCameraRelationDto.getOrgId());
                taskInfoDto.setBasicCamera(cameraMapper.selectById(taskCameraRelationDto.getCameraId()));

                //TODO 暂时为空
                taskInfoDto.setTask_content(JSON.toJSONString(new HashMap<String,Object>()));

                infoDtoList.add(taskInfoDto);
            }

//            HttpClientUtils.post(VideoTaskManage.startTask, JsonUtil.beanToString(infoDtoList));

            return Result.success(infoDtoList);
        }catch (Exception e){
            log.error("===根据编码获取任务信息异常===",e);
            return Result.failure("根据编码获取任务信息异常");
        }
    }

    @ApiOperation("获取任务的组织结构")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orgId",value = "组织id",required = true,paramType = "query")
    })
    @GetMapping("/getChildOrgIds")
    public Result<List<Integer>> getChildOrgIds(@RequestParam Integer orgId) {
        try {

            List<Integer> result=organizationMapper.getChildOrgIdsById(orgId);
            return Result.success(result);

        }catch (Exception e){
            log.error("获取组织子区域失败",e);
            return Result.failure("获取组织子区域失败");
        }
    }





}
